package cn.hs.lyxf.service.impl;

import cn.hs.lyxf.basic.ContractNo;
import cn.hs.lyxf.basic.JavaToPdfHtmlFreeMarker;
import cn.hs.lyxf.domain.*;
import cn.hs.lyxf.exception.GlobalErrorCode;
import cn.hs.lyxf.feign.MaintenanceFeign;
import cn.hs.lyxf.feign.SystemFeigen;
import cn.hs.lyxf.feign.UserFeign;
import cn.hs.lyxf.mapper.SignedOrderLogMapper;
import cn.hs.lyxf.mapper.SignedOrderMapper;
import cn.hs.lyxf.result.JsonResult;
import cn.hs.lyxf.service.ISignedOrderService;
import cn.hs.lyxf.utils.AssertUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mzy
 * @since 2022-12-09
 */
@Service
public class SignedOrderServiceImpl extends ServiceImpl<SignedOrderMapper, SignedOrder> implements ISignedOrderService {

    @Autowired
    private SignedOrderMapper signedOrderMapper;

    @Autowired
    private SignedOrderLogMapper signedOrderLogMapper;

    @Autowired
    private MaintenanceFeign maintenanceFeign;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private SystemFeigen systemFeigen;

    /**
     * 指派员工签约
     *
     * @param empId   员工ID
     * @param orderId 签约订单ID
     * @return 签约结果
     */
    @Override
    public JsonResult empSigned(Long empId, Long orderId) {
        // 判断员工是否存在
        Employee employee = systemFeigen.getId(empId);
        AssertUtil.isNotNull(employee, GlobalErrorCode.ERROR);
        // 判断员工是否有部门
        Long deptId = employee.getDeptId();
        AssertUtil.isTrue(deptId != null || deptId != 0, GlobalErrorCode.ERROR);
        // 部门是否存在
        Department department = systemFeigen.getById(deptId);
        AssertUtil.isNotNull(department, GlobalErrorCode.ERROR);
        // 员工状态是否正常
        Integer state = employee.getState();
        AssertUtil.isTrue(state == 0, GlobalErrorCode.ERROR);
        // 级别是否是经理部
        String name = department.getName();
        AssertUtil.isTrue(name.equals("经理部"), GlobalErrorCode.ERROR);
        // 根据签约订单ID查询签约订单信息
        SignedOrder signedOrder = signedOrderMapper.selectById(orderId);
        // 校验签约订单信息是否存在
        AssertUtil.isNotNull(signedOrder, GlobalErrorCode.ERROR);

        // 更新签约订单信息中的员工ID
        signedOrder.setEmpId(empId);
        // 更新签约订单信息
        signedOrderMapper.updateById(signedOrder);
        // 返回签约成功结果
        return JsonResult.success();
    }

    /**
     * 签约失败
     *
     * @param signedOrderLog 签约失败日志
     * @return 签约结果
     */
    @Override
    public JsonResult signedFail(SignedOrderLog signedOrderLog) {
        // 根据签约订单ID查询签约订单信息
        SignedOrder signedOrder = signedOrderMapper.selectById(signedOrderLog.getOrderId());
        // 校验签约订单信息是否存在
        AssertUtil.isNotNull(signedOrder, GlobalErrorCode.ERROR);
        // 修改签约订单状态为失败
        signedOrder.setState(-1);
        // 更新签约订单信息
        signedOrderMapper.updateById(signedOrder);
        // 设置签约失败日志的创建时间
        signedOrderLog.setCrateTime(new Date());
        // 保存签约失败日志
        signedOrderLogMapper.insert(signedOrderLog);
        // 返回签约失败结果
        return JsonResult.error();
    }

    /**
     * 签约成功
     *
     * @param
     * @return
     */
    @Override
    public JsonResult signedProsperity(SignedOrder order) throws Exception {
        Long orderId = order.getId();
        Integer signedYear = order.getSignedYear();
        if (orderId == null && signedYear == null) {
            return JsonResult.error("订单不合规");
        }
        // 业务校验
        SignedOrder signedOrder = signedOrderMapper.selectById(orderId);
        AssertUtil.isTrue(signedOrder.getState() == 0, GlobalErrorCode.ERROR);
        // 生成电子合同
        // 1.1.时间
        LocalDate now = LocalDate.now();
        int year = now.getYear() + signedYear;
        LocalDate localDate = LocalDate.now();
        LocalDate end = localDate.withYear(year);
        // 1.2.编号
        String sn = ContractNo.recountNew(10);
        Map<String, Object> data = new HashMap();
        data.put("开始年月日", now);
        data.put("到期年月日", end);
        data.put("合同编号", sn);
        // 1.3.姓名
        User user = userFeign.get(signedOrder.getUserId());
        String username = user.getNickName();
        data.put("甲方姓名", username);
        data.put("甲方负责人", username);
        data.put("签字日期", now);
        String content = JavaToPdfHtmlFreeMarker.freeMarkerRender(data, "h.html");
        JavaToPdfHtmlFreeMarker.createPdf(content, "D:\\lyxf\\" + "合同" + sn + ".pdf");
        // 新增维保表
        Maintenance maintenance = new Maintenance();
        maintenance.setCompanyDimension(order.getCompanyDimension());
        maintenance.setCrateTime(new Date());
        maintenance.setSignedYear(signedYear);
        maintenance.setTotalPrice(order.getTotalPrice());
        maintenance.setUserCompanyId(signedOrder.getCompanyId());
        maintenance.setUserCompanyPhone(signedOrder.getUserPhone());
        maintenance.setUserId(signedOrder.getUserId());
        maintenance.setUserCompanyId(signedOrder.getCompanyId());
        maintenanceFeign.saveOrUpdate(maintenance);
        // 修改签约单状态
        signedOrder.setState(1);
        signedOrder.setTotalPrice(order.getTotalPrice());
        signedOrder.setCompanyDimension(order.getCompanyDimension());
        signedOrder.setSignedYear(signedYear);
        signedOrder.setFinishTime(new Date());
        signedOrderMapper.updateById(signedOrder);
        return JsonResult.success();
    }
}
